#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
依赖分析器模块
提供准确的上下游依赖关系分析功能
"""

from typing import List, Dict, Any
from .models import ResourceEntitiesMap, ResourceDetails, RelationshipDefinition
from sqlalchemy.orm import Session


class DependencyAnalyzer:
    """依赖分析器类"""
    
    def __init__(self, db_session: Session):
        """
        初始化依赖分析器
        
        Args:
            db_session: 数据库会话对象
        """
        self.db = db_session
    
    def find_upstream_dependencies(self, resource_id: str) -> List[Dict[str, Any]]:
        """
        查找指定资源的上游依赖（指向该资源的节点）
        
        Args:
            resource_id: 资源ID
            
        Returns:
            上游依赖资源列表
        """
        upstream_resources = []
        
        # 查找指向当前节点的关系（入度边）
        incoming_relationships = self.db.query(ResourceEntitiesMap).filter_by(end_nodes_id=resource_id).all()
        
        for rel in incoming_relationships:
            start_node = self.db.query(ResourceDetails).filter_by(id=rel.start_nodes_id).first()
            if start_node:
                relationship_def = self.db.query(RelationshipDefinition).filter_by(id=rel.relation_id).first()
                upstream_resources.append({
                    'id': start_node.id,
                    'name': start_node.details_name,
                    'description': start_node.description,
                    'relationship': relationship_def.name if relationship_def else '未知关系',
                    'direction': 'upstream'
                })
        
        return upstream_resources
    
    def find_downstream_dependencies(self, resource_id: str) -> List[Dict[str, Any]]:
        """
        查找指定资源的下游依赖（从该资源出发的节点）
        
        Args:
            resource_id: 资源ID
            
        Returns:
            下游依赖资源列表
        """
        downstream_resources = []
        
        # 查找从当前节点出发的关系（出度边）
        outgoing_relationships = self.db.query(ResourceEntitiesMap).filter_by(start_nodes_id=resource_id).all()
        
        for rel in outgoing_relationships:
            end_node = self.db.query(ResourceDetails).filter_by(id=rel.end_nodes_id).first()
            if end_node:
                relationship_def = self.db.query(RelationshipDefinition).filter_by(id=rel.relation_id).first()
                downstream_resources.append({
                    'id': end_node.id,
                    'name': end_node.details_name,
                    'description': end_node.description,
                    'relationship': relationship_def.name if relationship_def else '未知关系',
                    'direction': 'downstream'
                })
        
        return downstream_resources
    
    def find_all_dependencies(self, resource_id: str) -> Dict[str, List[Dict[str, Any]]]:
        """
        查找指定资源的所有依赖关系（包括上游和下游）
        
        Args:
            resource_id: 资源ID
            
        Returns:
            包含上游和下游依赖的字典
        """
        return {
            'upstream': self.find_upstream_dependencies(resource_id),
            'downstream': self.find_downstream_dependencies(resource_id)
        }